package com.sites.cds.common;

import java.util.Date;
import java.util.Enumeration;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.sites.common.SiteInfo;
import com.sites.common.kit.IpKit;
import com.sites.common.model.Accesslog;

/**
 * cds访问记录拦截器<br/>
 * 和cms访问记录拦截器相互独立，更好地模块化、个性化扩展
 * 
 * @author zyg 
 * 2020年8月1日 下午10:41:57
 */
public class CdsAccessInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		inv.invoke();
		// 当启用访问日志记录时才记录日志
		if ("1".equals(SiteInfo.cdsAccessLog)) {
			Controller controller = inv.getController();
			Accesslog accesslog = new Accesslog();
			accesslog.setType(SiteInfo.cdsLog);// 设置类型为cds
			accesslog.setIp(IpKit.getIpAddress(controller.getRequest()));// 设置访问用户IP
			accesslog.setActionKey(inv.getActionKey());// 设置actionKey
			accesslog.setSiteId(SiteInfo.siteId);// 设置站点id
			// 记录请求参数
			String paras = getPara(controller);
			if(StrKit.notBlank(paras)){
				accesslog.setParameter(paras);
			}					
			accesslog.setAccessTime(new Date());
			accesslog.save();
		}
	}
	
	/**
	 * 获取请求中的para参数<br/>
	 * 代码参考JFinal中的调试模式下输出的请求信息
	 * 
	 * @param controller
	 * @return
	 */
	private String getPara(Controller controller){
		StringBuilder sb = new StringBuilder();
		
		// 获取urlParas
		String urlParas = controller.getPara();
		if (StrKit.notBlank(urlParas)) {
			sb.append("UrlPara     : ").append(urlParas).append("\n");
		}
		
		// 获取para参数
		Enumeration<String> paraNames = controller.getParaNames();
		if (paraNames.hasMoreElements()) {
			sb.append("Parameter   : ");
			while (paraNames.hasMoreElements()) {
				String name = paraNames.nextElement();
				String[] values = controller.getParaValues(name);
				if (values.length == 1) {
					sb.append(name).append("=");
					if (values[0] != null && values[0].length() > SiteInfo.paraValuesMaxLength) {
						sb.append(values[0].substring(0, 100)).append("...");
					} else {
						sb.append(values[0]);
					}
				} else {
					sb.append(name).append("[]={");
					for (int i = 0; i < values.length; i++) {
						if (i > 0){
							sb.append(",");
						}
						sb.append(values[i]);
					}
					sb.append("}");
				}
				sb.append("  ");
			}
		}
		return sb.toString();
	}

}
